import Cookies from 'js-cookie';
import {
  COOKIE_KEY_LANGUAGE,
  AVAILABLE_LANGUAGES,
  DEFAULT_LANGUAGE,
  COOKIE_DOMAIN_ATOMGIT,
} from './constants';

export const convertLanguageStringToAtomGit = (lang?: string) => {
  return lang?.replace('-', '_');
};

export const convertLanguageStringFromAtomGit = (lang?: string) => {
  return lang?.replace('_', '-');
};

export const getLanguageFromClient = () => {
  const language = convertLanguageStringFromAtomGit(Cookies.get(COOKIE_KEY_LANGUAGE)) ?? DEFAULT_LANGUAGE;

  if (!isAvailableLanguage(language)) {
    return DEFAULT_LANGUAGE;
  }

  return language;
};

export const setLanguageFromClient = (language: string) => {
  if (!isAvailableLanguage(language)) {
    return;
  }

  Cookies.set(COOKIE_KEY_LANGUAGE, convertLanguageStringToAtomGit(language) as string, {
    path: '/',
    expires: 3650,
    domain: import.meta.env.DEV ? undefined : COOKIE_DOMAIN_ATOMGIT,
  });
};

export const isAvailableLanguage = (lang: string) => AVAILABLE_LANGUAGES.some((item) => item === lang);
